<?php

namespace App\Models;


use App\Service\Base\Model;
use Illuminate\Support\Facades\DB;

class EventCollect extends Model
{

    // 用户收藏管理
    protected $table = 'event_collect';

    // 缓存字段，用于搜索绑定的字段
    protected $cacheFields = ['id', 'uid', 'article_id', 'channel', 'status'];

    //  {"id":"编号","channel":"各类文章来源（研学，赛事，文章，）","article_id":"文章ID","uid":"用户id","status":"收藏状态 1-收藏 0-取消收藏","ctime":"创建时间","mtime":"修改时间"}

    // array ( 'id' => '$this->getData("id", null, "trim")', 'channel' => '$this->getData("channel", null, "trim")', 'article_id' => '$this->getData("article_id", null, "trim")', 'uid' => '$this->getData("uid", null, "trim")', 'status' => '$this->getData("status", null, "trim")', 'ctime' => '$this->getData("ctime", null, "trim")', 'mtime' => '$this->getData("mtime", null, "trim")', )


    // $id = $this->getData("id", null, 'trim'); $channel = $this->getData("channel", null, 'trim'); $article_id = $this->getData("article_id", null, 'trim'); $uid = $this->getData("uid", null, 'trim'); $status = $this->getData("status", null, 'trim'); $ctime = $this->getData("ctime", null, 'trim'); $mtime = $this->getData("mtime", null, 'trim');


    // 收藏(第二次点击，取消收藏)
    public function onCollect($uid, $article_id)
    {
        // 赛事game,  研学study，沙龙salon
        /*if(in_array($channel, ['study', 'game', 'salon'])){
            $model = new Event();
        } elseif($channel == 'news'){
            // 文章
            $model = new News();
        } else{
            return $this->return_false('请指定文章正确的类型！');
        }*/

        // 事务操作
        $model = new Event();
        DB::beginTransaction();
        try{

            // 查看活动是否存在
            $where = ['id' => $article_id];  // , 'verify' => 1
            $info  = $model->where($where)->lockForUpdate()->first();
            if(empty($info)){
                throw new \Exception('你要收藏的内容不存在或者被禁用！');
            }

            // 是否已经关注
            $where  = ['uid' => $uid, 'article_id' => $article_id];
            $isInfo = $this->where($where)->lockForUpdate()->first();

            // 数据操作
            if(empty($isInfo)){
                $status   = 1;
                $follData = ['uid' => $uid, 'article_id' => $article_id, 'status' => 1];
                $numbers  = ['collect_no' => DB::raw('collect_no + 1')];
                $this->fill($follData);
            } else{
                if($isInfo['status'] == 1){
                    $status   = 0;
                    $follData = ['status' => 0];
                    $numbers  = ['collect_no' => DB::raw('collect_no - 1')];
                } else{
                    $status   = 1;
                    $follData = ['status' => 1];
                    $numbers  = ['collect_no' => DB::raw('collect_no + 1')];
                }
                $isInfo->fill($follData);
            }

            // 关注
            if(empty($isInfo)){
                $result = $this->save();
            } else{
                $result = $isInfo->save();
            }

            // 关注人数
            $model->where('id', $article_id)->update($numbers);

            // 提交事务
            DB::commit();
        } catch(\Exception $e){
            // 回滚事务
            DB::rollback();
            $error = $this->getError() ?: $e->getMessage();

            return $this->return_false($error, 5000);
        }

        // 缓存操作
        //$userDb->reSaveCache($uid, $numCache);
        $this->deleteCacheShow($follData, $isInfo);
        $model->deleteCacheShow(['id' => $article_id]);

        return $status;
    }

    // 收藏(第二次点击，取消收藏)
    public function isCollect($uid, $article_id)
    {
        if(empty($uid) || empty($article_id)){
            return 0;
        }

        // 赛事game,  研学study，沙龙salon
        /*if(in_array($channel, ['study', 'game', 'salon'])){
        } elseif($channel == 'news'){
        } else{
            return $this->return_false('请指定文章正确的类型！');
        }*/

        // 是否已经关注
        $where  = ['uid' => $uid, 'article_id' => $article_id];
        $isInfo = $this->isCache(true)->oneFind($where);

        // 数据操作
        $status = 0;
        if($isInfo && ($isInfo['status'] == 1)){
            $status = 1;
        }

        return $status;
    }

    // 获取用户的订阅用户（我关注的人）
    public function getCollect($where, $page = 1, $rows = 10, $order = "id DESC")
    {
        // 获取缓存
        $bang     = $this->bang;
        $is_cache = $this->is_cache || $bang;
        $args     = compact('where', 'page', 'rows', 'order');
        if($is_cache){
            $cacheName = $this->cacheKey('lists_getFollow', $args);
            $result    = $this->cacheClass()->getCache($cacheName);
            // 检查是否已经绑定
            if(($result) && (!empty($result['table']))){
                $this->checkBangList($result['table'], $cacheName);
            }
        }

        // 查询
        if(empty($result)){
            $query = $this->where($where)->forPage($page, $rows);
            $count = $this->where($where)->count();
            if(is_array($order)){

            } else{
                $order = explode(" ", $order);
                $query = $query->orderby($order[0], $order[1]);
            }
            $lists = $query->get()->toArray();
        } else{
            $lists = $result['table'];
        }


        // 获取用户
        $users = [];
        if($lists){
            $userDb = new User();
            $uids   = array_column($lists, 'to_uid');
            $lists  = array_column($lists, null, 'to_uid');
            $users  = $userDb->isCache(true)->getListInIds($uids);
            foreach($users as $key => $_user){
                $_userid = $_user['id'];
                $_row    = $lists[$_userid] ?? [];
                // 整理
                $users[$key]['collect_time'] = $_row['mtime'] ?? 0;
            }
        }

        $result = ['count' => $count, 'page' => $page, 'rows' => $rows, 'list' => $users, 'table' => $lists,];
        // 保存为缓存
        if($is_cache && $lists){
            $this->addCacheList($lists, $cacheName, $result, 'list');
            $userDb->addBangList($users, $cacheName);
        }

        return $result;
    }


    // 定义验证操作
    public function rules()
    {

        $add = [
        ];

        $edit = [
        ];

        $info = [
        ];


        $rule = [
            'channel'    => 'required',
            'article_id' => 'required',
            'uid'        => 'required',
            'status'     => 'in:0,1',
        ];


        $msg = [
            'id'         => '编号',
            'channel'    => '各类文章来源（研学，赛事，文章，）',
            'article_id' => '文章ID',
            'uid'        => '用户id',
            'status'     => '收藏状态 1-收藏 0-取消收藏',
            'ctime'      => '创建时间',
            'mtime'      => '修改时间',
        ];

        return ['rule' => $rule, 'msg' => $msg, 'add' => $add];
    }
}
